package com.kai.demo.controller;

import com.kai.demo.RedisApplication;
import com.kai.demo.consts.RedisKey;
import com.kai.demo.entity.User;
import com.kai.demo.service.UserService;
import com.kai.demo.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: sprigncloud-demo </p>
 * <p>Description: </p>
 * <p>Copyright (c) 2024 Karrytech (Shanghai/Beijing) Co., Ltd.</p>
 * <p>All Rights Reserved.</p>
 *
 * @author <a href="mailto:zhangkai@karrytech.com">Zhang Kai</a>
 */
@RestController
@RequestMapping("/kai/redis/user")
public class UserController {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/save")
    public void save(@RequestBody User user) {
        userService.save(user);
        redisUtil.set(RedisKey.USER + ":" + user.getId(), RedisApplication.JsonUtil.toJson(user), 12000);
    }

    @RequestMapping("/get")
    public User get(@RequestParam Integer id) {
        String redisKey = RedisKey.USER + ":" + id;
        try {
            if (redisUtil.hasKey(redisKey)) {
                logger.info("from: redis");
                Object o = redisUtil.get(redisKey);
                return (User) o;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = userService.get(id);
        if (user != null) {
            redisUtil.set(redisKey, user, 12000);
        }
        return user;
    }

    @GetMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();
    }

    @GetMapping("/anno")
    public String anno(){
        return "不需要认证可以访问";
    }

    // 测试注解
    @RequestMapping("/testSecured")
    @ResponseBody
    @Secured({"ROLE_普通用户","ROLE_管理员"})
    public String helloUser() {
        return "hello,user";
    }

    @RequestMapping("/preAuthorize")
    @ResponseBody
//@PreAuthorize("hasRole('ROLE_管理员')")
    @PreAuthorize("hasAnyAuthority('menu:system')")
    public String preAuthorize(){
        System.out.println("preAuthorize");
        return "preAuthorize";
    }

}